#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <errno.h>
#include <stddef.h>
#include <unistd.h>
#include "nvml.h"

#define MAX_CONNECT_NUM 2
#define BUFFER_SIZE 1024
const char *server_path  = "/var/run/nvstat.sock";
char *client_path = "client.socket"; 

#define MAXLINE 80  

int test() {  
    struct  sockaddr_un cliun, serun;  
    int len;  
    char buf[100];  
    int sockfd, n;  
 
    if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){  
        perror("client socket error");  
        exit(1);  
    }  
      
    // 一般显式调用bind函数，以便服务器区分不同客户端  
    memset(&cliun, 0, sizeof(cliun));  
    cliun.sun_family = AF_UNIX;  
    strcpy(cliun.sun_path, client_path);  
    len = offsetof(struct sockaddr_un, sun_path) + strlen(cliun.sun_path);  
    unlink(cliun.sun_path);  
    if (bind(sockfd, (struct sockaddr *)&cliun, len) < 0) {  
        perror("bind error");  
        exit(1);  
    }  
 
    memset(&serun, 0, sizeof(serun));  
    serun.sun_family = AF_UNIX;  
    strcpy(serun.sun_path, server_path);  
    len = offsetof(struct sockaddr_un, sun_path) + strlen(serun.sun_path);  
    if (connect(sockfd, (struct sockaddr *)&serun, len) < 0){  
        perror("connect error");  
        exit(1);  
    }  
 
    while ( n = read(sockfd, buf, MAXLINE)) {
               write(STDOUT_FILENO, buf, n);
    }

    printf("\n");

    while(0) { //(fgets(buf, MAXLINE, stdin) != NULL) {    
         write(sockfd, buf, strlen(buf));    
         n = read(sockfd, buf, MAXLINE);    
         if ( n < 0 ) {    
            printf("the other side has been closed.\n");    
         }else {    
            write(STDOUT_FILENO, buf, n);    
         }    
    }   
    close(sockfd);  
    return 0;  
}  

int main() {
//        while(1) {
                test();
//                sleep(3);
//        }
}

main_old(){   
        int fd, new_fd, len, i;
        struct sockaddr_un un;
        int ret;
        char buffer[1024];
        int n;
        int left = sizeof(buffer);
        char *p = buffer;

        fd = socket(AF_UNIX, SOCK_STREAM, 0);
        if(fd < 0){
                perror("Request socket failed.");
                return -1;
        }
        
        if (connect(fd, (struct sockaddr *) &un, sizeof(struct sockaddr_un)) < 0) {
                perror("connect");
                close(fd);
                exit(1);
        }
        while ( n = read(fd, p, left) >= 0) {
                p += n;
                left -= n;
        }
        close(fd);
        printf("%s\n", buffer);
  }
